根據官方文件給的方法上傳
https://firebase.google.com/docs/storage/ios/upload-files
程式碼:
//
// ViewController.swift
// Dog Breed Recognition App
//
// Created by PecaJo on 2021/6/24.
import UIKit
import FirebaseStorage
class ViewController: UIViewController {
@IBOutlet weak var uploadButton: UIButton!
@IBOutlet weak var libraryButton: UIButton!
@IBOutlet weak var imageview: UIImageView!
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
self.imagePicker.delegate = self
// Do any additional setup after loading the view.
}
@IBAction func clickuploadbutton(_ sender: Any) {
if imageview.image != nil {
uploadFile()
}
else{
let alertController = UIAlertController(title: "圖片訊息", message: "請放入圖片", preferredStyle: UIAlertController.Style.alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
present(alertController, animated: true, completion: nil)
}
}
@IBAction func clicklibrarybutton(_ sender: Any) {
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true)
}
func uploadFile(){
let url = URL(string: "https://XXXXXXXXXXXXXXXXXXXXXXXXXXX")
// Create a root reference
let storageRef = Storage.storage().reference()
// Data in memory
let imageData: Data = imageview.image!.jpegData(compressionQuality: 1.0)!
// Create a reference to the file you want to upload
let riversRef = storageRef.child("dog.jpg")
// Upload the file to the path "images/rivers.jpg"
let uploadTask = riversRef.putData(imageData, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
// Uh-oh, an error occurred!
return
}
// Metadata contains file metadata such as size, content-type.
let size = metadata.size
// You can also access to download URL after upload.
riversRef.downloadURL { (url, error) in
guard let downloadURL = url else {
// Uh-oh, an error occurred!
return
}
}
}
}
}
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
imageview.contentMode = .scaleAspectFit
imageview.image = pickedImage
imageview.layer.masksToBounds = true;
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}